﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using MyLib.Data;
using MyLib.Web.UI;

namespace MyLib.Web.Pages {
	/// <summary>
	/// 
	/// </summary>
	public abstract class MyMessagesPage : MyPage {
		/// <summary>
		/// 
		/// </summary>
		protected void DoQuery() {
			var gridView = this.FindDescendantControl<MyGridView>("GridView1");

			gridView.PageIndex = 0;
			gridView.DataBind();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="messageId"></param>
		protected void DoReadMessage(string messageId) {
			if (messageId == null || messageId.Length == 0) {
				return;
			}

			ViewState["ReadMessageId"] = messageId;

			this.FindDescendantControl<System.Web.UI.Control>("FormView1").DataBind();

			this.FindDescendantControl<System.Web.UI.Control>("GridView1").DataBind();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="causesValidation"></param>
		/// <param name="validationGroup"></param>
		protected virtual void HandleQuery(bool causesValidation, string validationGroup) {
			this.FindDescendantControl<MyPanel>("Panel1").CopyValuesToViewState(ViewState);

			Context.ExecuteSafely(DoQuery);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected bool HasRead() {
			var row = (System.Data.DataRowView) Page.GetDataItem();

			var messageId = row.Get<string>("messageId").Trim();
			var hasRead = row.Get<int>("hasRead");

			return hasRead != 0;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			// Add object datasources.
			var ds1 = new MyObjectDataSource(typeof(MyLib.Data.MessagesProvider).AssemblyQualifiedName, "FindMessages");
			ds1.ID = "ObjectDataSource1";
			ds1.SelectCountMethod = "FindMessagesCount";
			ds1.EnableCaching = false;
			ds1.EnablePaging = true;

			ds1.SelectParameters.Add(new MyUserParameter {
				Name = "receiverId",
				Type = TypeCode.String
			});
			ds1.SelectParameters.Add(new MyViewStateParameter {
				Name = "senderId",
				Type = TypeCode.String,
				Key = "SenderIdToMatch"
			});
			ds1.SelectParameters.Add(new MyViewStateParameter {
				Name = "title",
				Type = TypeCode.String,
				Key = "TitleToMatch"
			});
			ds1.SelectParameters.Add(new MyViewStateParameter {
				Name = "content",
				Type = TypeCode.String,
				Key = "ContentToMatch"
			});
			ds1.SelectParameters.Add(new MyViewStateParameter {
				Name = "hasRead",
				Type = TypeCode.Boolean,
				Key = "HasReadToMatch"
			});
			ds1.SelectParameters.Add(new MyViewStateParameter {
				Name = "status",
				Type = TypeCode.Int32,
				Key = "StatusToMatch",
				DefaultValue = "1"
			});

			var ds2 = new MyObjectDataSource(typeof(MyLib.Data.MessagesProvider).AssemblyQualifiedName, "ReadById");
			ds2.ID = "ObjectDataSource2";
			ds2.EnableCaching = false;
			ds2.EnablePaging = false;

			ds2.SelectParameters.Add(new MyUserParameter {
				Name = "receiverId",
				Type = TypeCode.String
			});
			ds2.SelectParameters.Add(new MyViewStateParameter {
				Name = "messageId",
				Type = TypeCode.String,
				Key = "ReadMessageId"
			});

			var ds3 = new MyCodeDataSource();
			ds3.ID = "CodeDataSource1";
			ds3.Items.Add(new CodeItem {
				Text = Properties.Main.Unread,
				Value = "false"
			});
			ds3.Items.Add(new CodeItem {
				Text = Properties.Main.Read,
				Value = "true"
			});

			Controls.Add(ds1);
			Controls.Add(ds2);
			Controls.Add(ds3);

			// Assign event handlers.

			var gridView1 = this.FindDescendantControl<MyGridView>("GridView1");
			gridView1.DataSourceID = ds1.ID;
			gridView1.AllowPaging = true;

			gridView1.RowCommand += new GridViewCommandEventHandler(OnGridView1RowCommand);

			var formView1 = this.FindDescendantControl<MyFormView>("FormView1");
			formView1.DataSourceID = ds2.ID;
			formView1.Cancelled += new EventHandler<MyFormViewCommandEventArgs>(OnFormView1Cancelled);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			this.Title = Properties.Main.TitleMyMessages;

			if (!IsPostBack) {
				this.FindDescendantControl<MyPanel>("Panel1").CopyValuesToViewState(ViewState);

				Context.ExecuteSafely(DoQuery);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="source"></param>
		/// <param name="args"></param>
		/// <returns></returns>
		protected override bool OnBubbleEvent(object source, EventArgs args) {
			bool causesValidation = false;
			string validationGroup = string.Empty;

			if (args is CommandEventArgs) {
				IButtonControl commandSource = source as IButtonControl;
				if (commandSource != null) {
					causesValidation = commandSource.CausesValidation;
					validationGroup = commandSource.ValidationGroup;
				}

				var cargs = (CommandEventArgs)args;

				if (string.Equals(cargs.CommandName, "Query", StringComparison.OrdinalIgnoreCase)) {
					HandleQuery(causesValidation, validationGroup);
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		} // end of OnBubbleEvent.

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected virtual void OnGridView1RowCommand(object sender, GridViewCommandEventArgs e) {
			var arg = (string)e.CommandArgument;

			var messageId = arg;

			Action act;
			switch (e.CommandName) {
				case "ReadMessage":
					act = () => DoReadMessage(messageId);
					break;
				default:
					return;
			}

			Context.ExecuteSafely(act);
		} // end of OnGridView1RowCommand.

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnFormView1Cancelled(object sender, MyFormViewCommandEventArgs e) {
			ViewState["ReadMessageId"] = null;
		} // end of OnFormView1Cancelled.
	} // end of CodePage.
}
